package monsmon.util;

import java.util.*;
import java.io.*;
import java.util.regex.*;

/*
 * A parser for Config files.
 * basic format:
 * OPTION = VALUE;
 * #Comment
 */
public class ConfigParser{

	private static String option = "(:?\\w*)";

	private static String assign_s = "^\\s*" + option + "\\s*=\\s*"
			+ Util.argument + "\\s*";

	private static Pattern assign = Pattern.compile(assign_s);

	private static Pattern comment = Pattern.compile("\\#.*$");

	public static void parse_config(InputStream instrs){
		HashMap<String, String> opts = new HashMap<>();
		BufferedReader rdr = null;
		try{
			rdr = Util.instream_to_bufdrdr(instrs);
		}catch(IOException e){
			e.printStackTrace();
			return;
		}
		try{
			for(String line = rdr.readLine(); line != null;
					rdr.readLine()){
				Matcher m = comment.matcher(line);
				line = m.replaceAll("");
				m = assign.matcher(line);
				if(m.matches()){
					opts.put(m.group(1), m.group(2));
				}else if("".equals(line.trim())){
					//Comment, do nothing
				}else{
					//ERROR!
				}
				line = rdr.readLine();
			}
		}catch(IOException ex){
			//ERROR, shouldn't happen
			return;
		}
		Config.__add(opts);
	}

}
